package com.yfl.config;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yfl.constant.GatewallConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.List;

/**
 * JWT的校验
 */
@Component
public class JWTCheckFilter implements GlobalFilter, Ordered {

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 1.拿到请求
     * 2.判断放行的路径
     * 3.拿到请求头
     * 4.拿到jwt
     * 5.判断
     * 6返回401
     *
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 拿到请求地址
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();
        if (GatewallConstant.ALLOW_URLS.contains(path)) {
            // 放行
            return chain.filter(exchange);
        }
        HttpHeaders headers = request.getHeaders();
        List<String> auths = headers.get(GatewallConstant.AUTHORIZATION);
        if (!CollectionUtils.isEmpty(auths)) {
            String authorization = auths.get(0);
            if (StringUtils.hasText(authorization)) {
                // 分割
                String jwt = authorization.replaceAll(GatewallConstant.BEARER_PREFIX, "");
                if (StringUtils.hasText(jwt) && redisTemplate.hasKey(GatewallConstant.OAUTH_PREFIX + jwt)) {
                    // 放行
                    return chain.filter(exchange);
                }

            }
        }
        // 拦截 返回401 前台会帮你跳转到登录页面
        ServerHttpResponse response = exchange.getResponse();
        response.getHeaders().add("content-type", "application/json;charest=utf-8");
        // 组装业务返回值
        HashMap<String, Object> map = new HashMap<>(4);
        map.put("code", HttpStatus.UNAUTHORIZED.value());
        map.put("msg", "未授权");
        ObjectMapper objectMapper = new ObjectMapper();
        byte[] bytes = new byte[0];
        try {
            bytes = objectMapper.writeValueAsBytes(map);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        DataBuffer wrap = response.bufferFactory().wrap(bytes);
        return response.writeWith(Mono.just(wrap));
    }

    @Override
    public int getOrder() {
        return -1;
    }
}
